﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinFormsApp1.RelationForms;

namespace WinFormsApp1
{
    public partial class FormRelationPreview : Form
    {
        private List<DataColumInfo> m_selectedColumns;
        private Dictionary<string, List<EntityInfo>> m_allEntities;

        public FormRelationPreview(List<DataColumInfo> nodes)
        {
            m_selectedColumns = nodes;
            InitializeComponent();
        }

        private void FormRelationPreview_Load(object sender, EventArgs e)
        {
            //找到所有的实体
            m_allEntities = new Dictionary<string, List<EntityInfo>>();
            for (var i = 0; i < m_selectedColumns.Count; i++)
            {
                var dt = m_selectedColumns[i].RefExcel;
                var keyField = m_selectedColumns[i].ColumnName;

                var entityNames = dt.EntityColumns;

                for (var j = 0; j < entityNames.Count; j++)
                {
                    for (var k = 0; k < dt.RefDataTable.Rows.Count; k++)
                    {
                        var entityColumnInfo = entityNames[j];
                        //这里定义了标准的名词
                        var entityName = dt.RefDataTable.Rows[k][entityColumnInfo.ColumnName].ToString();
                        entityName = entityColumnInfo.Prefix + entityName + entityColumnInfo.Postfix;

                        var entityKey = dt.RefDataTable.Rows[k][keyField].ToString();

                        var key = m_selectedColumns[i].TableName + "-" + entityNames[j].ColumnName;
                        if (m_allEntities.ContainsKey(key) == false)
                        {
                            m_allEntities.Add(key, new List<EntityInfo>());
                        }

                        m_allEntities[key].Add(
                            new EntityInfo()
                            {
                                EntityColumn = entityColumnInfo,
                                ConnectKey = entityKey,
                                EntityName = entityName,
                                TableColumn = m_selectedColumns[i],
                                RowIndex = k
                            });
                    }
                }
            }

            //Distinct所有实体
            var allEntityName = m_allEntities.Keys.ToList();

            this.comboBox1.Items.AddRange(allEntityName.ToArray());
            this.comboBox2.Items.AddRange(allEntityName.ToArray());

            BuildRelationPair();
        }

        /// <summary>
        /// 拿取实体去构建关系对
        /// </summary>
        private void BuildRelationPair()
        {
            this.listView1.Items.Clear();
            var filter1 = this.comboBox1.Text;
            if (string.IsNullOrEmpty(filter1))
            {
                filter1 = null;
            }
            var filter2 = this.comboBox2.Text;
            if (string.IsNullOrEmpty(filter2))
            {
                filter2 = null;
            }
            var allEntityName = m_allEntities.Keys.ToList();
            for (var i = 0; i < allEntityName.Count; i++)
            {
                if (filter1 != null && filter1 != allEntityName[i])
                {
                    continue;
                }
                var items1 = m_allEntities[allEntityName[i]];
                for (var j = i + 1; j < allEntityName.Count; j++)
                {
                    if (filter2 != null && filter2 != allEntityName[j])
                    {
                        continue;
                    }
                    var items2 = m_allEntities[allEntityName[j]];

                    BuildRelationPair(items1, items2);
                }
            }
        }
        private void BuildRelationPair(List<EntityInfo> items1, List<EntityInfo> items2)
        {
            for (var i = 0; i < items1.Count; i++)
            {
                for (var j = 0; j < items2.Count; j++)
                {
                    if (items1[i].ConnectKey != items2[j].ConnectKey)
                    {
                        continue;
                    }
                    ListViewItem lvi = new ListViewItem(items1[i].EntityName
                        + "(" + items1[i].EntityColumn + ")");
                    lvi.SubItems.Add(items1[i].ConnectKey);
                    lvi.SubItems.Add(items2[j].EntityName + "(" + items2[j].EntityColumn + ")");

                    lvi.Tag = new EntityInfo[]
                    {
                        items1[i],
                        items2[j],
                    };

                    this.listView1.Items.Add(lvi);
                }
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count == 0) return;
            var entityInfos = this.listView1.SelectedItems[0].Tag as EntityInfo[];

            ShowProperity(entityInfos[0], this.listView2, textBox1, textBox3);
            ShowProperity(entityInfos[1], this.listView3, textBox2, textBox4);
        }
        private void ShowProperity(EntityInfo p1, ListView listView, TextBox tableNameBox, TextBox fieldNameBox)
        {
            listView.Items.Clear();
            listView.Columns.Clear();

            listView.Columns.Add("Key", 150);
            listView.Columns.Add("Value", 300);
            tableNameBox.Text = p1.TableColumn.TableName;
            fieldNameBox.Text = p1.EntityColumn.ColumnName;

            for (var i = 0; i < p1.TableColumn.RefExcel.Columns.Count; i++)
            {
                var key = p1.TableColumn.RefExcel.Columns[i].ColumnName;
                var value = p1.TableColumn.RefExcel.RefDataTable.Rows[p1.RowIndex][key];

                ListViewItem lvi = new ListViewItem(key);
                lvi.SubItems.Add(value.ToString());

                listView.Items.Add(lvi);
            }
        }

        private void 单独导出d3jToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormRelationExporter dlg = new FormRelationExporter(this.listView1);
            dlg.StartPosition = FormStartPosition.CenterScreen;
            dlg.Show();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            BuildRelationPair();
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            BuildRelationPair();
        }

        private void 复制名称ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selItem = this.listView2.SelectedItems.Count > 0 ? this.listView2.SelectedItems[0] : null;
            if (selItem == null)
                selItem = this.listView3.SelectedItems.Count > 0 ? this.listView3.SelectedItems[0] : null;
            if (selItem != null)
            {
                Clipboard.SetText("{" + selItem.Text + "}");
            }
        }
    }

    class EntityInfo
    {
        /// <summary>
        /// 定义实体如何命名的。这个命名是唯一的。
        /// </summary>
        public EntityNaming EntityColumn { get; set; }
        public string EntityName;
        /// <summary>
        /// 定义这个实体如何跟外界进行关联,
        /// 可以有TableColumn推倒
        /// </summary>
        public string ConnectKey; 
        /// <summary>
        /// 在整个数据表中的信息
        /// </summary>
        public DataColumInfo TableColumn;
        public int RowIndex;
    }

    class EntityInfoComparer : IComparer<EntityInfo>
    {
        public int Compare(EntityInfo? x, EntityInfo? y)
        {
            return x.ConnectKey.CompareTo(y.ConnectKey);
        }
    }
}
